package com.gxa.modules.sys.controller;

import com.gxa.common.utils.MD5Utils;
import com.gxa.common.utils.Result;
import com.gxa.common.utils.TPage;
import com.gxa.modules.sys.entity.User;
import com.gxa.modules.sys.form.UserForm;
import com.gxa.modules.sys.service.UserService;
import com.gxa.modules.sys.service.UserTokenService;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Map;

import static cn.hutool.core.lang.Console.log;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhuiyi
 * @since 2022-10-29 04:01:04
 */
@Api(tags = "用户接口2222")
@RestController
@RequestMapping("/user")
@Slf4j
@AllArgsConstructor
public class UserController {

    private UserService userService;
    private UserTokenService userTokenService;

    @ApiOperation("我的登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody UserForm user){
        log.info("------------>{}",user);
        //1.为空校验
        if(StringUtils.isAnyBlank(user.getUsername(), user.getPassword())){

            return new Result().error("用户名或密码不能为空！");
        }
        //2.根据用户名查询用户信息
        User dbUser = this.userService.queryByUsername(user.getUsername());
        if(dbUser == null){
            return new Result().error("用户名或密码错误!");
        }
        //3.将明文密码加密 与密文密码比较
        String encodePassword = MD5Utils.encrypt(user.getUsername(),user.getPassword());
        if(!encodePassword.equals(dbUser.getPassword())){
            return new Result().error("用户名或密码错误!");
        }
        //4.密码相同，登录成功 创建token 放redis
        Result result = userTokenService.createToken(dbUser);
        Map<String,Object> map = new HashMap<>();
        //Authorization 过滤器拦截
        map.put("token",result.getData());
        return new Result().ok(map);
    }

    @ApiOperation("用户列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "pageNum",value = "当前在那一页",dataType = "int"),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页多少条记录",dataType = "int"),
            @ApiImplicitParam(paramType = "query",name = "username",value = "用户名",dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "id",value = "用户id",dataType = "int"),
            @ApiImplicitParam(paramType = "query",name = "orderField",value = "根据什么字段排序",dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "order",value = "升序-asc 降序-desc （不是asc都是降序）",dataType = "String"),
    })
    @GetMapping("/list")
    public Result list(@RequestParam @ApiIgnore HashMap<String,Object> searchMap){
        log.info("---------------{}-------------",searchMap);
        TPage tPage = userService.queryByPage(searchMap);
        return new Result().ok(tPage);
    }
}
